import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)


export const store = new Vuex.Store({
    state: {
        // 定义保存数据的对象
        userinfo: {},
        cars: [],
    },
    mutations: {
        // 定义用于更新数据的方法
        setUserInfo(state, user) {
            // localStorage中存储是防止刷新浏览器时数据丢失
            localStorage.setItem('userinfo', JSON.stringify(user))
            state.userinfo = user
        },
        // 添加商品
        addGoods(state, goodsList) {
            state.cars = goodsList
            // let goods = goodsList
            // const flag = state.cars.some(v => {
            //   if (v.id == goods.id) {
            //     v.count = goods.count
            //     return true
            //   }
            // })
            // if (!flag) {
            //   state.cars.push(goods)
            // }
            // console.log(state.cars);
          },
          // 删除商品
          removeGoods(state, goodsId) {
              // console.log('数据共享的',state.cars);
            const index = state.cars.findIndex(v => v.id === goodsId)
            state.cars.splice(index, 1)
          }
    },
    getters:{
        // 计算总数量和总价格
        goodsCP(state) {
            let allCount = 0
            let allPrice = 0
            // console.log(state.cars);
            state.cars.forEach(v => {
              allCount += v.count
              if (v.ischecked) {
                allPrice += v.count * v.price * 100
              }
            })
            // console.log('数量',allCount);
            // console.log('总价格',allPrice);
            return {
              allCount,
              allPrice
            }
          }
    }
})